<template>
  <div class="system-log-container">
    <h1>系统日志</h1>
    <div class="search-section">
             <div class="search-form">
         <div class="form-row">
           <div class="form-item">
             <label>请求地址:</label>
             <input v-model="searchParams.RequestUrl" type="text" placeholder="请求地址" />
           </div>
           <div class="form-item">
             <label>用户IP:</label>
             <input v-model="searchParams.UserIP" type="text" placeholder="用户IP" />
           </div>
           <div class="form-item">
             <label>服务器IP:</label>
             <input v-model="searchParams.ServerIP" type="text" placeholder="服务器IP" />
           </div>
           <div class="form-item">
             <label>响应状态:</label>
             <select v-model="searchParams.ResponseStatus">
               <option value="">响应状态</option>
               <option value="成功">成功</option>
               <option value="失败">失败</option>
             </select>
           </div>
           <div class="form-item">
             <label>开始时间:</label>
             <input v-model="searchParams.StartTimeFrom" type="datetime-local" />
           </div>
           <div class="form-item">
             <label>至</label>
             <input v-model="searchParams.StartTimeTo" type="datetime-local" />
           </div>
           <div class="form-item">
             <label>用户名称:</label>
             <input v-model="searchParams.UserName" type="text" placeholder="用户名称" />
           </div>
         </div>
        <div class="form-row">
          <div class="form-item log-types">
            <label>日志类型:</label>
            <div class="checkbox-group">
              <label v-for="type in logTypes" :key="type" class="checkbox-item">
                <input type="checkbox" v-model="selectedLogTypes" :value="type" />
                <span>{{ type }}</span>
              </label>
            </div>
          </div>
        </div>
      </div>
      <div class="action-buttons">
        <button class="btn btn-primary" @click="handleSearch">🔍 查询</button>
        <button class="btn btn-secondary" @click="handleReset">🔄 重置</button>
        <button class="btn btn-danger" @click="handleBatchDelete" :disabled="selectedLogIds.length === 0">🗑️ 批量删除</button>
        <button class="btn btn-success" @click="handleExport">⬇️ 导出</button>
        <button class="btn btn-info" @click="showColumnSettings">⚙️ 设置</button>
        <button class="btn btn-warning" @click="emergencyFixColumns">🚨 紧急修复</button>
        <div class="feature-hint">
          💡 点击设置按钮可以自定义表格列的显示和顺序
          <br>
          🚨 如果发现重复列，请点击紧急修复按钮
        </div>
        <div v-if="selectedLogIds.length > 0" class="selection-info">
          📋 已选择 <span class="selection-count">{{ selectedLogIds.length }}</span> 条日志
        </div>
      </div>
    </div>

    <div class="table-section">
      <h3>系统日志</h3>

      <!-- 错误信息显示 -->
      <div v-if="errorMessage" class="error-message">
        <span class="error-icon">⚠️</span>
        {{ errorMessage }}
      </div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <span>正在加载数据...</span>
      </div>
      
      <!-- 数据表格 -->
      <div v-else-if="systemLogs.length > 0" class="table-container">
        <el-table 
          :data="systemLogs" 
          v-loading="loading" 
          stripe 
          border 
          style="width: 100%" 
          max-height="600"
          :scrollbar-always-on="true"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          
          <!-- 动态列渲染 -->
          <el-table-column 
            v-for="column in visibleColumns" 
            :key="column.key"
            :prop="column.key" 
            :label="column.label" 
            :width="column.width" 
            :sortable="column.sortable"
            :align="getColumnAlign(column.key)"
          >
            <template #default="scope">
              <!-- 开始时间列 -->
              <template v-if="column.key === 'StartTime'">
                {{ formatDateTime(scope.row.StartTime) }}
              </template>
              
              <!-- 请求地址列 -->
              <template v-else-if="column.key === 'RequestUrl'">
                <span class="url-cell" :title="scope.row.RequestUrl">{{ truncateUrl(scope.row.RequestUrl) }}</span>
              </template>
              
              <!-- 日志类型列 -->
              <template v-else-if="column.key === 'LogType'">
                <el-tag type="info" size="small">{{ scope.row.LogType }}</el-tag>
              </template>
              
              <!-- 响应状态列 -->
              <template v-else-if="column.key === 'ResponseStatus'">
                <el-tag 
                  :type="scope.row.ResponseStatus === '成功' ? 'success' : 'danger'" 
                  size="small"
                >
                  {{ scope.row.ResponseStatus }}
                </el-tag>
              </template>
              
              <!-- 时长列 -->
              <template v-else-if="column.key === 'Duration'">
                {{ scope.row.Duration }}ms
              </template>
              
              <!-- 请求参数列 -->
              <template v-else-if="column.key === 'RequestParams'">
                <span class="params-cell" :title="scope.row.RequestParams">{{ truncateText(scope.row.RequestParams, 30) }}</span>
              </template>
              
              <!-- 其他列 -->
              <template v-else>
                {{ getLogValue(scope.row, column.key) }}
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 无数据状态 -->
      <div v-else-if="!loading && systemLogs.length === 0" class="no-data-container">
        <div class="no-data">
          <p>暂无数据</p>
          <p class="no-data-hint">请检查查询条件或重新查询</p>
        </div>
      </div>
    </div>

    <div class="pagination-section">
      <div class="pagination-info">
        <span>共{{ totalCount }}条</span>
        <span class="page-detail">第{{ currentPage }}/{{ totalPage }}页</span>
        <span class="page-detail">每页{{ pageSize }}条</span>
      </div>
      <div class="pagination-controls">
        <select v-model="pageSize" @change="handlePageSizeChange">
          <option value="6">6条/页</option>
          <option value="10">10条/页</option>
          <option value="30">30条/页</option>
          <option value="50">50条/页</option>
          <option value="100">100条/页</option>
        </select>
        <div class="pagination-buttons">
          <button class="page-btn" @click="handlePageChange(currentPage - 1)" :disabled="currentPage <= 1">&lt;</button>
          
          <!-- 显示页码 -->
          <template v-if="totalPage <= 7">
            <!-- 总页数较少时，显示所有页码 -->
            <button 
              v-for="page in totalPage" 
              :key="page"
              class="page-btn" 
              :class="{ 'current-page': page === currentPage }"
              @click="handlePageChange(page)"
            >
              {{ page }}
            </button>
          </template>
          <template v-else>
            <!-- 总页数较多时，显示部分页码 -->
            <!-- 第一页 -->
            <button 
              class="page-btn" 
              :class="{ 'current-page': currentPage === 1 }"
              @click="handlePageChange(1)"
            >
              1
            </button>
            
            <!-- 省略号 -->
            <span v-if="currentPage > 4" class="page-ellipsis">...</span>
            
            <!-- 当前页附近的页码 -->
            <button 
              v-for="page in getVisiblePages()" 
              :key="page"
              class="page-btn" 
              :class="{ 'current-page': page === currentPage }"
              @click="handlePageChange(page)"
            >
              {{ page }}
            </button>
            
            <!-- 省略号 -->
            <span v-if="currentPage < totalPage - 3" class="page-ellipsis">...</span>
            
            <!-- 最后一页 -->
            <button 
              v-if="totalPage > 1"
              class="page-btn" 
              :class="{ 'current-page': currentPage === totalPage }"
              @click="handlePageChange(totalPage)"
            >
              {{ totalPage }}
            </button>
          </template>
          
          <button class="page-btn" @click="handlePageChange(currentPage + 1)" :disabled="currentPage >= totalPage">&gt;</button>
        </div>
        
        <!-- 页码跳转 -->
        <div class="page-jump">
          <span>跳转到</span>
          <input 
            v-model.number="jumpPage" 
            type="number" 
            min="1" 
            :max="totalPage"
            @keyup.enter="handleJumpPage"
            placeholder="页码"
          />
          <span>页</span>
          <button class="page-btn" @click="handleJumpPage">确定</button>
        </div>
      </div>
    </div>

    <!-- 列设置对话框 -->
    <div v-if="showSettings" class="modal-overlay" @click="closeColumnSettings">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>⚙️ 设置</h3>
          <button class="close-btn" @click="closeColumnSettings">×</button>
        </div>
        <div class="modal-body">
          <div class="column-list" ref="columnListRef">
            <div 
              v-for="(column, index) in allColumns" 
              :key="column.key" 
              class="column-item"
              :class="{
                'dragging': draggedIndex === index,
                'drag-over': draggedOverIndex === index && draggedIndex !== index
              }"
              draggable="true"
              @dragstart="handleDragStart($event, index)"
              @dragover="handleDragOver($event, index)"
              @drop="handleDrop($event, index)"
              @dragend="handleDragEnd"
            >
              <div class="drag-handle">⋮⋮</div>
              <label class="column-checkbox">
                <input 
                  type="checkbox" 
                  v-model="column.visible" 
                  @change="updateVisibleColumns"
                />
                <span class="column-number">{{ index + 1 }}</span>
                <span class="column-label">{{ column.label }}</span>
              </label>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeColumnSettings">✕ 取消</button>
          <button class="btn btn-success" @click="resetColumnSettings">🔄 重置</button>
          <button class="btn btn-primary" @click="confirmColumnSettings">✓ 确定</button>
        </div>
      </div>
    </div>

    <!-- 批量删除确认对话框 -->
    <div v-if="showDeleteConfirm" class="modal-overlay" @click="closeDeleteConfirm">
      <div class="modal-content delete-confirm-modal" @click.stop>
        <div class="modal-header delete-header">
          <h3>⚠️ 批量删除确认</h3>
          <button class="close-btn" @click="closeDeleteConfirm">×</button>
        </div>
        <div class="modal-body">
          <div class="delete-confirm-content">
            <div class="warning-icon">🚨</div>
            <div class="confirm-message">
              <p class="main-text">您即将删除选中的 <span class="highlight-count">{{ selectedLogIds.length }}</span> 条系统日志</p>
              <p class="warning-text">此操作不可恢复，请确认是否继续？</p>
              <div class="selected-ids">
                <span class="label">选中的日志ID:</span>
                <span class="ids">{{ selectedLogIds.join(', ') }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeDeleteConfirm">✕ 取消</button>
          <button class="btn btn-danger" @click="confirmBatchDelete">🗑️ 确认删除</button>
        </div>
      </div>
    </div>

    <!-- 删除结果对话框 -->
    <div v-if="showDeleteResult" class="modal-overlay" @click="closeDeleteResult">
      <div class="modal-content delete-result-modal" @click.stop>
        <div class="modal-header" :class="{ 'success-header': deleteResult?.Success, 'error-header': !deleteResult?.Success }">
          <h3>{{ deleteResult?.Success ? '✅ 删除完成' : '❌ 删除失败' }}</h3>
          <button class="close-btn" @click="closeDeleteResult">×</button>
        </div>
        <div class="modal-body">
          <div class="delete-result-content">
            <div v-if="deleteResult?.Success" class="success-icon">🎉</div>
            <div v-else class="error-icon">💥</div>
            
            <div class="result-message">
              <div class="result-summary">
                <p><strong>删除结果:</strong></p>
                <ul>
                  <li>成功删除: <span class="success-count">{{ deleteResult?.DeletedCount }}</span> 条</li>
                  <li>失败: <span class="error-count">{{ deleteResult?.FailedCount }}</span> 条</li>
                </ul>
              </div>
              
              <div v-if="deleteResult?.FailedCount > 0 && deleteResult?.FailedSysLogsIds.length > 0" class="failed-ids">
                <p><strong>失败的日志ID:</strong></p>
                <span class="failed-ids-list">{{ deleteResult.FailedSysLogsIds.join(', ') }}</span>
              </div>
              
              <div v-if="deleteResult?.DeleteReason" class="delete-reason">
                <p><strong>删除原因:</strong></p>
                <span class="reason-text">{{ deleteResult.DeleteReason }}</span>
              </div>
              
              <div class="operation-time">
                <p><strong>操作时间:</strong></p>
                <span class="time-text">{{ formatOperationTime(deleteResult?.OperationTime) }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-primary" @click="closeDeleteResult">✓ 确定</button>
        </div>
      </div>
    </div>

    <!-- 导出成功提示 -->
    <div v-if="showExportSuccessModal" class="modal-overlay" @click="closeExportSuccessModal">
      <div class="modal-content export-success-modal" @click.stop>
        <div class="modal-header">
          <h3>✅ 导出成功</h3>
          <button class="close-btn" @click="closeExportSuccessModal">×</button>
        </div>
        <div class="modal-body">
          <div class="export-success-content">
            <div class="success-icon">🎉</div>
            <p>{{ exportSuccessMessage }}</p>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-primary" @click="closeExportSuccessModal">✓ 确定</button>
        </div>
      </div>
    </div>

    <!-- 导出失败提示 -->
    <div v-if="showExportErrorModal" class="modal-overlay" @click="closeExportErrorModal">
      <div class="modal-content export-error-modal" @click.stop>
        <div class="modal-header">
          <h3>❌ 导出失败</h3>
          <button class="close-btn" @click="closeExportErrorModal">×</button>
        </div>
        <div class="modal-body">
          <div class="export-error-content">
            <div class="error-icon">💥</div>
            <p>{{ exportErrorMessage }}</p>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-primary" @click="closeExportErrorModal">✓ 确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { querySystemLogs, exportSystemLogs, deleteSystemLogs, batchDeleteSystemLogs, type SystemLog, type SystemLogQueryParams } from '@/api/systemLog'

// 日志类型列表
const logTypes = [
  '用户添加', '用户查询', '图片上传', '用户批量删除', 
  '用户数据导出', '用户导入模板下载', '用户数据导入'
]

// 响应式数据
const systemLogs = ref<SystemLog[]>([])
const totalCount = ref(0)
const totalPage = ref(0)
const currentPage = ref(1)
const pageSize = ref(6)  // 改为6条/页
const jumpPage = ref(1)
const selectedLogIds = ref<number[]>([])
const selectedLogTypes = ref<string[]>([])
const loading = ref(false) // 添加加载状态
const errorMessage = ref('') // 添加错误信息

// 搜索参数
const searchParams = reactive<SystemLogQueryParams>({
  RequestUrl: '',
  UserIP: '',
  UserName: '',
  ServerIP: '',
  StartTimeFrom: '',
  StartTimeTo: '',
  ResponseStatus: '',
  RoleId: undefined,
  LogType: '',
  PageIndex: 1,
  PageSize: 6  // 改为6条/页
})

// 列设置
const allColumns = ref([
  { key: 'StartTime', label: '开始时间', visible: true, sortable: true, width: '180px', cellClass: '', sortKey: '' },
  { key: 'UserName', label: '用户名称', visible: true, sortable: true, width: '120px', cellClass: '', sortKey: '' },
  { key: 'RequestUrl', label: '请求地址', visible: true, sortable: true, width: '300px', cellClass: 'url-cell', sortKey: '' },
  { key: 'LogType', label: '日志类型', visible: true, sortable: true, width: '140px', cellClass: '', sortKey: '' },
  { key: 'ResponseStatus', label: '响应状态', visible: true, sortable: true, width: '120px', cellClass: '', sortKey: '' },
  { key: 'Duration', label: '时长', visible: true, sortable: true, width: '100px', cellClass: '', sortKey: '' },
  { key: 'RequestParams', label: '请求参数', visible: true, sortable: true, width: '350px', cellClass: 'params-cell', sortKey: '' },
  { key: 'ResponseParams', label: '响应参数', visible: true, sortable: false, width: '200px', cellClass: '', sortKey: '' },
  { key: 'ExceptionInfo', label: '异常信息', visible: true, sortable: true, width: '300px', cellClass: 'exception-cell', sortKey: '' },
  { key: 'UserIP', label: '用户IP', visible: true, sortable: true, width: '140px', cellClass: '', sortKey: '' },
  { key: 'BrowserType', label: '浏览器类型', visible: true, sortable: true, width: '500px', cellClass: '', sortKey: '' },
])

// 从本地存储加载列设置
const loadColumnSettings = () => {
  try {
    const savedSettings = localStorage.getItem('systemLogColumnSettings')
    if (savedSettings) {
      const settings = JSON.parse(savedSettings)
      // 验证设置的有效性
      const validSettings: Record<string, boolean> = {}
      allColumns.value.forEach(col => {
        if (settings[col.key] !== undefined && typeof settings[col.key] === 'boolean') {
          validSettings[col.key] = settings[col.key]
          col.visible = settings[col.key]
        } else {
          col.visible = true // 默认可见
        }
      })
      
      // 如果设置无效，清理本地存储
      if (Object.keys(validSettings).length !== Object.keys(settings).length) {
        console.warn('检测到无效的列设置，正在清理...')
        localStorage.removeItem('systemLogColumnSettings')
        saveColumnSettings() // 保存默认设置
      }
    }
  } catch (error) {
    console.warn('加载列设置失败:', error)
    // 清理损坏的设置
    localStorage.removeItem('systemLogColumnSettings')
  }
}

// 保存列设置到本地存储
const saveColumnSettings = () => {
  try {
    const settings: Record<string, boolean> = {}
    allColumns.value.forEach(col => {
      settings[col.key] = col.visible
    })
    localStorage.setItem('systemLogColumnSettings', JSON.stringify(settings))
  } catch (error) {
    console.warn('保存列设置失败:', error)
  }
}

const visibleColumns = computed(() => {
  const visible = allColumns.value.filter(col => col.visible)
  // 确保列的唯一性，防止重复
  const uniqueColumns = visible.filter((col, index, self) => 
    index === self.findIndex(c => c.key === col.key)
  )
  
  // 如果发现重复列，记录警告
  if (visible.length !== uniqueColumns.length) {
    console.warn('⚠️ 检测到重复列，正在自动去重')
    console.warn('原始可见列数量:', visible.length)
    console.warn('去重后列数量:', uniqueColumns.length)
  }
  
  // 调试信息
  console.log('=== 列配置调试信息 ===')
  console.log('所有列:', allColumns.value.map(col => ({ key: col.key, label: col.label, visible: col.visible })))
  console.log('可见列:', visible.map(col => ({ key: col.key, label: col.label })))
  console.log('去重后列:', uniqueColumns.map(col => ({ key: col.key, label: col.label })))
  
  return uniqueColumns
})

const showSettings = ref(false)
const columnListRef = ref<HTMLElement>()
const draggedIndex = ref(-1)
const draggedOverIndex = ref(-1)

// 批量删除相关状态
const showDeleteConfirm = ref(false)
const showDeleteResult = ref(false)
const deleteResult = ref<any>(null)

// 导出成功/失败提示相关状态
const showExportSuccessModal = ref(false)
const showExportErrorModal = ref(false)
const exportSuccessMessage = ref('')
const exportErrorMessage = ref('')

// 计算属性
const isAllSelected = computed(() => {
  return systemLogs.value.length > 0 && selectedLogIds.value.length === systemLogs.value.length
})

// Element Plus表格选择相关
const handleSelectionChange = (selection: SystemLog[]) => {
  selectedLogIds.value = selection.map(log => log.SysLogsId)
}

// 获取列对齐方式
const getColumnAlign = (key: string) => {
  switch (key) {
    case 'LogType':
    case 'ResponseStatus':
    case 'Duration':
      return 'center'
    default:
      return 'left'
  }
}

// 方法
const loadSystemLogs = async () => {
  loading.value = true
  errorMessage.value = ''
  
  try {
    const params = { ...searchParams }
    
    // 处理日志类型
    if (selectedLogTypes.value.length > 0) {
      params.LogType = selectedLogTypes.value.join(',')
    }
    
    // 处理分页
    params.PageIndex = currentPage.value
    params.PageSize = pageSize.value
    
    console.log('=== 系统日志API请求开始 ===')
    console.log('请求参数:', params)
    console.log('API地址:', '/api/Login/querySystemLogs')
    console.log('API主机:', 'MES_XHY_ApiHost (http://localhost:5216)')
    
    const response = await querySystemLogs(params)
    console.log('=== API响应详情 ===')
    console.log('完整响应对象:', response)
    console.log('响应状态码:', response.status)
    console.log('响应数据:', response.data)
    
    if (response.data && response.data.code === 200) {
      systemLogs.value = response.data.PageData || []
      totalCount.value = response.data.TotalCount || 0
      totalPage.value = response.data.TotalPage || 0
      
      // 确保当前页不超过总页数
      if (currentPage.value > totalPage.value && totalPage.value > 0) {
        currentPage.value = totalPage.value
      }
      
      console.log('=== 数据加载成功 ===')
      console.log('总记录数:', totalCount.value)
      console.log('总页数:', totalPage.value)
      console.log('当前页数据条数:', systemLogs.value.length)
      console.log('当前页数据:', systemLogs.value)
      console.log('当前页码:', currentPage.value)
      
      if (systemLogs.value.length === 0) {
        console.log('⚠️ 注意: API返回成功但数据为空')
        errorMessage.value = '查询成功，但未找到符合条件的日志数据'
      }
    } else {
      const errorMsg = response.data?.msg || '查询失败'
      errorMessage.value = `API返回错误: ${errorMsg}`
      console.error('❌ API返回错误:', response.data)
    }
  } catch (error: any) {
    console.error('=== 网络请求异常 ===')
    console.error('错误类型:', error.constructor.name)
    console.error('错误详情:', error)
    console.error('错误消息:', error.message)
    
    if (error.response) {
      // 服务器响应了错误状态码
      console.error('服务器响应状态:', error.response.status)
      console.error('服务器响应数据:', error.response.data)
      errorMessage.value = `服务器错误 (${error.response.status}): ${error.response.data?.message || error.response.statusText}`
    } else if (error.request) {
      // 请求已发出但没有收到响应
      console.error('请求已发出但无响应')
      errorMessage.value = '网络连接失败，请检查后端服务是否正常运行'
    } else {
      // 其他错误
      errorMessage.value = `请求配置错误: ${error.message}`
    }
  } finally {
    loading.value = false
    console.log('=== 请求完成 ===')
  }
}

const handleSearch = () => {
  currentPage.value = 1
  // 使用真实API调用
  loadSystemLogs()
  // filterMockData() // 注释掉模拟数据搜索
}

// 模拟数据过滤函数 - 注释掉
// const filterMockData = () => {
//   // 重新加载模拟数据
//   loadMockData()
//   
//   // 这里可以添加过滤逻辑
//   // 例如根据searchParams过滤数据
//   console.log('搜索参数:', searchParams)
//   console.log('选中的日志类型:', selectedLogTypes.value)
// }

const handleReset = () => {
  Object.assign(searchParams, {
    RequestUrl: '',
    UserIP: '',
    UserName: '',
    ServerIP: '',
    StartTimeFrom: '',
    StartTimeTo: '',
    ResponseStatus: '',
    RoleId: undefined,
    LogType: '',
    PageIndex: 1,
    PageSize: 6  // 改为6条/页
  })
  selectedLogTypes.value = []
  selectedLogIds.value = []
  currentPage.value = 1
  // 使用真实API调用
  loadSystemLogs()
  // loadMockData() // 注释掉模拟数据
}



const handleDelete = async () => {
  if (selectedLogIds.value.length === 0) {
    alert('请选择要删除的日志')
    return
  }
  
  if (confirm('确定要删除选中的日志吗？')) {
    try {
      const response = await deleteSystemLogs(selectedLogIds.value)
      if (response.data.code === 200) {
        alert('删除成功')
        selectedLogIds.value = []
        loadSystemLogs()
      } else {
        alert(response.data.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      alert('删除失败')
    }
  }
}

// 批量删除系统日志
const handleBatchDelete = async () => {
  if (selectedLogIds.value.length === 0) {
    alert('请选择要删除的日志')
    return
  }
  
  // 显示确认对话框
  showDeleteConfirm.value = true
}

const handleExport = async () => {
  try {
    // 显示导出加载状态
    const exportButton = document.querySelector('.btn-success') as HTMLButtonElement
    const originalText = exportButton.textContent
    exportButton.textContent = '⏳ 导出中...'
    exportButton.disabled = true
    
    // 准备导出参数，包含所有搜索条件
    const params = { ...searchParams }
    
    // 处理日志类型
    if (selectedLogTypes.value.length > 0) {
      params.LogType = selectedLogTypes.value.join(',')
    }
    
    // 移除分页参数，导出所有数据
    delete params.PageIndex
    delete params.PageSize
    
    console.log('=== 导出系统日志开始 ===')
    console.log('导出参数:', params)
    console.log('API地址:', '/api/Login/exportSystemLogs')
    console.log('请求方法:', 'GET')
    
    const response = await exportSystemLogs(params)
    console.log('=== 导出响应 ===')
    console.log('响应状态:', response.status)
    console.log('响应类型:', response.headers['content-type'])
    console.log('响应大小:', response.data.size, 'bytes')
    
    // 检查响应类型
    const contentType = response.headers['content-type']
    if (!contentType || !contentType.includes('excel') && !contentType.includes('spreadsheet')) {
      console.warn('⚠️ 响应类型可能不是Excel文件:', contentType)
    }
    
    // 创建Blob对象
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    
    // 生成文件名
    const timestamp = new Date().toISOString().split('T')[0]
    const fileName = `系统日志_${timestamp}.xlsx`
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    link.style.display = 'none'
    
    // 添加到DOM并触发下载
    document.body.appendChild(link)
    link.click()
    
    // 清理
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    console.log('=== 导出成功 ===')
    console.log('文件名:', fileName)
    console.log('文件大小:', blob.size, 'bytes')
    
    // 显示成功提示
    showExportSuccess(fileName, blob.size)
    
  } catch (error: any) {
    console.error('=== 导出失败 ===')
    console.error('错误类型:', error.constructor.name)
    console.error('错误详情:', error)
    console.error('错误消息:', error.message)
    
    let errorMessage = '导出失败'
    
    if (error.response) {
      // 服务器响应了错误状态码
      console.error('服务器响应状态:', error.response.status)
      console.error('服务器响应数据:', error.response.data)
      
      if (error.response.status === 401) {
        errorMessage = '导出失败：未授权，请重新登录'
      } else if (error.response.status === 403) {
        errorMessage = '导出失败：权限不足'
      } else if (error.response.status === 404) {
        errorMessage = '导出失败：API接口不存在'
      } else if (error.response.status === 500) {
        errorMessage = '导出失败：服务器内部错误'
      } else {
        errorMessage = `导出失败：服务器错误 (${error.response.status})`
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      console.error('请求已发出但无响应')
      errorMessage = '导出失败：网络连接失败，请检查后端服务是否正常运行'
    } else {
      // 其他错误
      errorMessage = `导出失败：${error.message}`
    }
    
    // 显示错误提示
    showExportError(errorMessage)
    
  } finally {
    // 恢复按钮状态
    const exportButton = document.querySelector('.btn-success') as HTMLButtonElement
    if (exportButton) {
      exportButton.textContent = '⬇️ 导出'
      exportButton.disabled = false
    }
  }
}

// 获取可见的页码
const getVisiblePages = () => {
  const pages = []
  const start = Math.max(2, currentPage.value - 1)
  const end = Math.min(totalPage.value - 1, currentPage.value + 1)
  
  for (let i = start; i <= end; i++) {
    if (i > 1 && i < totalPage.value) {
      pages.push(i)
    }
  }
  return pages
}

const handlePageChange = (page: number) => {
  if (page >= 1 && page <= totalPage.value) {
    currentPage.value = page
    jumpPage.value = page // 同步跳转页码输入框
    loadSystemLogs() // 调用真实API
  }
}

const handlePageSizeChange = () => {
  currentPage.value = 1
  jumpPage.value = 1 // 重置跳转页码
  loadSystemLogs() // 调用真实API
}

const handleJumpPage = () => {
  const page = parseInt(jumpPage.value.toString())
  if (page >= 1 && page <= totalPage.value) {
    currentPage.value = page
    loadSystemLogs() // 调用真实API
  } else {
    alert(`页码必须在1-${totalPage.value}之间`)
    jumpPage.value = currentPage.value // 重置为当前页
  }
}

const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN')
}

const truncateUrl = (url: string) => {
  if (!url) return '-'
  return url.length > 50 ? url.substring(0, 50) + '...' : url
}

const truncateText = (text: string, maxLength: number) => {
  if (!text) return '-'
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
}

// 列设置相关方法
const showColumnSettings = () => {
  // 在显示设置前，先检查列配置的完整性
  const duplicateKeys = allColumns.value.map(col => col.key).filter((key, index, self) => 
    self.indexOf(key) !== index
  )
  
  if (duplicateKeys.length > 0) {
    console.error('❌ 检测到重复的列key:', duplicateKeys)
    alert('检测到列配置错误，正在自动修复...')
    resetColumnSettings()
    return
  }
  
  showSettings.value = true
}

const closeColumnSettings = () => {
  showSettings.value = false
}

const updateVisibleColumns = () => {
  // 当用户手动切换列的可见性时，实时更新显示
  // 不需要重新加载数据，只需要重新计算visibleColumns
}

const resetColumnSettings = () => {
  // 重置为默认列配置
  allColumns.value.forEach(col => {
    col.visible = true // 将所有列设置为可见
  })
  
  // 清理本地存储
  localStorage.removeItem('systemLogColumnSettings')
  
  // 保存设置
  saveColumnSettings()
  
  console.log('列设置已重置为默认配置')
  console.log('本地存储已清理')
}

// 紧急修复列配置
const emergencyFixColumns = () => {
  console.log('🚨 开始紧急修复列配置...')
  
  // 清理本地存储
  localStorage.removeItem('systemLogColumnSettings')
  
  // 重置列配置
  resetColumnSettings()
  
  // 强制刷新页面
  setTimeout(() => {
    window.location.reload()
  }, 1000)
  
  alert('列配置已修复，页面将在1秒后刷新')
}

const confirmColumnSettings = () => {
  // 在保存前检查列配置的完整性
  const duplicateKeys = allColumns.value.map(col => col.key).filter((key, index, self) => 
    self.indexOf(key) !== index
  )
  
  if (duplicateKeys.length > 0) {
    console.error('❌ 保存前检测到重复的列key:', duplicateKeys)
    alert('列配置有误，请重新设置')
    return
  }
  
  // 保存设置到本地存储
  saveColumnSettings()
  closeColumnSettings()
}

const handleSort = (key: string) => {
  // 简单的升序/降序排序
  const column = allColumns.value.find(col => col.key === key)
  if (column) {
    if (column.sortKey === 'asc') {
      column.sortKey = 'desc'
    } else {
      column.sortKey = 'asc'
    }
    // 重新加载数据以应用新的排序
    loadSystemLogs()
  }
}

const getSortIcon = (key: string) => {
  const col = allColumns.value.find(col => col.key === key)
  if (!col) return ''
  if (col.sortKey === 'asc') {
    return '↑'
  } else if (col.sortKey === 'desc') {
    return '↓'
  }
  return ''
}

// 获取日志值的通用方法
const getLogValue = (log: SystemLog, key: string) => {
  switch (key) {
    case 'StartTime':
      return formatDateTime(log.StartTime)
    case 'RequestUrl':
      return truncateUrl(log.RequestUrl)
    case 'ResponseStatus':
      return log.ResponseStatus
    case 'Duration':
      return `${log.Duration}ms`
    case 'RequestParams':
      return truncateText(log.RequestParams, 30)
    case 'ResponseParams':
      return '-'
    case 'ExceptionInfo':
      return log.ExceptionInfo || '-'
    case 'UserName':
      return log.UserName
    case 'LogType':
      return log.LogType
    case 'UserIP':
      return log.UserIP
    case 'BrowserType':
      return log.BrowserType
    default:
      return '-'
  }
}

// 拖拽排序相关方法
const handleDragStart = (event: DragEvent, index: number) => {
  draggedIndex.value = index
  if (event.dataTransfer) {
    event.dataTransfer.effectAllowed = 'move'
  }
}

const handleDragOver = (event: DragEvent, index: number) => {
  event.preventDefault()
  if (event.dataTransfer) {
    event.dataTransfer.dropEffect = 'move'
  }
  draggedOverIndex.value = index
}

const handleDrop = (event: DragEvent, index: number) => {
  event.preventDefault()
  if (draggedIndex.value !== -1 && draggedIndex.value !== index) {
    // 重新排列列顺序
    const columns = [...allColumns.value]
    const draggedColumn = columns[draggedIndex.value]
    columns.splice(draggedIndex.value, 1)
    columns.splice(index, 0, draggedColumn)
    allColumns.value = columns
    saveColumnSettings() // 保存新的列顺序
  }
  draggedIndex.value = -1
  draggedOverIndex.value = -1
}

const handleDragEnd = () => {
  draggedIndex.value = -1
  draggedOverIndex.value = -1
}

// 批量删除相关方法
const closeDeleteConfirm = () => {
  showDeleteConfirm.value = false
}

const confirmBatchDelete = async () => {
  closeDeleteConfirm() // 关闭确认对话框
  
  try {
    console.log('=== 批量删除开始 ===')
    console.log('选中的日志ID:', selectedLogIds.value)
    console.log('API地址: /api/Login/batchDeleteSystemLogs')
    console.log('请求参数:', { SysLogsIds: selectedLogIds.value })
    
    const response = await batchDeleteSystemLogs(selectedLogIds.value)
    console.log('批量删除响应:', response)
    
    if (response.data.code === 200) {
      const result = response.data.data
      deleteResult.value = {
        Success: true,
        DeletedCount: result.DeletedCount,
        FailedCount: result.FailedCount,
        FailedSysLogsIds: result.FailedSysLogsIds,
        DeleteReason: result.DeleteReason,
        OperationTime: result.OperationTime
      }
      showDeleteResult.value = true
      selectedLogIds.value = []
      loadSystemLogs()
      console.log('=== 批量删除成功 ===')
    } else {
      const errorMsg = response.data?.msg || '批量删除失败'
      deleteResult.value = {
        Success: false,
        DeletedCount: 0,
        FailedCount: 0,
        FailedSysLogsIds: [],
        DeleteReason: errorMsg,
        OperationTime: new Date().toISOString()
      }
      showDeleteResult.value = true
      console.error('❌ 批量删除失败:', response.data)
    }
  } catch (error: any) {
    console.error('=== 批量删除异常 ===')
    console.error('错误类型:', error.constructor.name)
    console.error('错误详情:', error)
    console.error('错误消息:', error.message)
    
    let errorMessage = '❌ 批量删除失败'
    
    if (error.response) {
      // 服务器响应了错误状态码
      console.error('服务器响应状态:', error.response.status)
      console.error('服务器响应数据:', error.response.data)
      errorMessage = `❌ 服务器错误 (${error.response.status})\n\n${error.response.data?.message || error.response.statusText}`
    } else if (error.request) {
      // 请求已发出但没有收到响应
      console.error('请求已发出但无响应')
      errorMessage = '❌ 网络连接失败\n\n请检查后端服务是否正常运行'
    } else {
      // 其他错误
      errorMessage = `❌ 请求配置错误\n\n${error.message}`
    }
    
    deleteResult.value = {
      Success: false,
      DeletedCount: 0,
      FailedCount: 0,
      FailedSysLogsIds: [],
      DeleteReason: errorMessage,
      OperationTime: new Date().toISOString()
    }
    showDeleteResult.value = true
  }
}

const closeDeleteResult = () => {
  showDeleteResult.value = false
  deleteResult.value = null
}

const formatOperationTime = (time: string) => {
  if (!time) return '-'
  try {
    return new Date(time).toLocaleString('zh-CN')
  } catch (error) {
    return time
  }
}

// 导出成功提示函数
const showExportSuccess = (fileName: string, fileSize: number) => {
  exportSuccessMessage.value = `✅ 导出成功！\n\n📁 文件名: ${fileName}\n📊 文件大小: ${(fileSize / 1024).toFixed(2)} KB`
  showExportSuccessModal.value = true
}

// 导出失败提示函数
const showExportError = (errorMessage: string) => {
  exportErrorMessage.value = errorMessage
  showExportErrorModal.value = true
}

// 关闭导出成功提示
const closeExportSuccessModal = () => {
  showExportSuccessModal.value = false
  exportSuccessMessage.value = ''
}

// 关闭导出失败提示
const closeExportErrorModal = () => {
  showExportErrorModal.value = false
  exportErrorMessage.value = ''
}

// 生命周期
onMounted(() => {
  // 加载真实数据
  loadSystemLogs()
  // loadMockData() // 注释掉模拟数据
  loadColumnSettings() // 加载列设置
  
  // 强制刷新列设置，确保没有重复
  console.log('=== 组件挂载完成，检查列配置 ===')
  console.log('当前可见列数量:', visibleColumns.value.length)
  console.log('当前可见列:', visibleColumns.value.map(col => ({ key: col.key, label: col.label })))
  
  // 自动检测并修复重复列
  const duplicateKeys = allColumns.value.map(col => col.key).filter((key, index, self) => 
    self.indexOf(key) !== index
  )
  
  if (duplicateKeys.length > 0) {
    console.error('❌ 自动检测到重复的列key:', duplicateKeys)
    console.log('正在自动修复...')
    emergencyFixColumns()
  }
})

// 模拟数据加载函数 - 注释掉
// const loadMockData = () => {
//   // 模拟API响应数据
//   const mockResponse = {
//     totalCount: 377,
//     totalPage: 38,
//     pageData: [
//       {
//         sysLogsId: 377,
//         startTime: "2025-08-15T14:53:41",
//         userId: 1,
//         userName: "admin",
//         requestUrl: "http://localhost:5216/api/Login/uploadImage",
//         logType: "图片上传",
//         responseStatus: "成功",
//         duration: 3,
//         requestParams: "{\"FileName\":\"\\u3010\\u54F2\\u98CE\\u58C1\\u7EB8\\u3011\\u4E2A\\u6027\\u80CC\\u666F-\\u590D\\u53E4\\u5899\\u9762.png\",\"FileSize\":2094229,\"ContentType\":\"image/png\"}",
//         exceptionInfo: "",
//         userIP: "::1",
//         browserType: "Chrome",
//         isDelete: false
//       },
//       {
//         sysLogsId: 376,
//         startTime: "2025-08-15T14:52:30",
//         userId: 2,
//         userName: "user001",
//         requestUrl: "http://localhost:5216/api/Login/login",
//         logType: "登陆",
//         responseStatus: "成功",
//         duration: 150,
//         requestParams: "{\"username\":\"user001\",\"password\":\"******\"}",
//         exceptionInfo: "",
//         userIP: "192.168.1.100",
//         browserType: "Firefox",
//         isDelete: false
//       },
//       {
//         sysLogsId: 375,
//         startTime: "2025-08-15T14:51:15",
//         userId: 3,
//         userName: "operator",
//         requestUrl: "http://localhost:5216/api/User/addUser",
//         logType: "新建",
//         responseStatus: "失败",
//         duration: 2000,
//         requestParams: "{\"name\":\"新用户\",\"email\":\"invalid-email\"}",
//         exceptionInfo: "邮箱格式不正确",
//         userIP: "192.168.1.101",
//         browserType: "Edge",
//         isDelete: false
//       }
//     ],
//     code: 200,
//     msg: "查询成功",
//     data: null
//   }
//   
//   // 设置模拟数据
//   systemLogs.value = mockResponse.pageData
//   totalCount.value = mockResponse.totalCount
//   totalPage.value = mockResponse.totalPage
// }
</script>

<style scoped>
/* 统一缩放工具类（优先使用 zoom，fallback 为 transform） */
.scale-90 { zoom: 0.9; }
.scale-85 { zoom: 0.85; }
.scale-80 { zoom: 0.8; }

@supports not (zoom: 1) {
  .scale-90 { transform: scale(0.9); transform-origin: top left; width: 111.12%; }
  .scale-85 { transform: scale(0.85); transform-origin: top left; width: 117.65%; }
  .scale-80 { transform: scale(0.8); transform-origin: top left; width: 125%; }
}
.system-log-container {
  padding: 10px;
  background-color: #f5f5f5;
  min-height: 100vh;
  height: auto;
  overflow: visible;
}

h1 {
  margin-bottom: 10px;
  color: #333;
  font-size: 16px;
}

/* 搜索区域 */
.search-section {
  background: white;
  border-radius: 8px;
  padding: 10px;
  margin-bottom: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  position: relative;
  z-index: 10;
}

.search-form {
  margin-bottom: 10px;
}

.form-row {
  display: flex;
  gap: 6px;
  margin-bottom: 6px;
  align-items: flex-end;
  flex-wrap: wrap;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 120px;
  max-width: 160px;
  flex: 0 1 auto;
}

.form-item.log-types {
  min-width: 100%;
  flex: none;
}

.form-item input,
.form-item select {
  padding: 5px 7px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 11px;
  height: 28px;
  box-sizing: border-box;
}

.form-item input[type="datetime-local"] {
  min-width: 120px;
  max-width: 160px;
}

.form-item label {
  font-weight: 500;
  color: #333;
  font-size: 11px;
  margin-bottom: 2px;
}

.checkbox-group {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  gap: 5px;
  margin-top: 6px;
  padding: 6px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.checkbox-item {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  font-size: 11px;
  padding: 2px 5px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.checkbox-item:hover {
  background-color: #e9ecef;
}

.checkbox-item input[type="checkbox"] {
  margin: 0;
  width: 12px;
  height: 12px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  align-items: center;
}

.feature-hint {
  margin-left: auto;
  color: #909399;
  font-size: 11px;
  font-style: italic;
  padding: 5px 7px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.selection-info {
  margin-left: 12px;
  color: #409eff;
  font-size: 11px;
  font-weight: 500;
  padding: 5px 8px;
  background-color: #f0f9ff;
  border-radius: 6px;
  border: 1px solid #bae6fd;
  display: flex;
  align-items: center;
  gap: 4px;
}

.selection-count {
  font-weight: 600;
  color: #f56c6c;
  background-color: #fef0f0;
  padding: 2px 6px;
  border-radius: 4px;
  border: 1px solid #fbc4c4;
  min-width: 20px;
  text-align: center;
}

.btn {
  padding: 5px 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 11px;
  transition: all 0.3s;
}

.btn-primary {
  background-color: #409eff;
  color: white;
}

.btn-primary:hover {
  background-color: #337ecc;
}

.btn-secondary {
  background-color: #67c23a;
  color: white;
}

.btn-secondary:hover {
  background-color: #529b2e;
}

.btn-danger {
  background-color: #f56c6c;
  color: white;
}

.btn-danger:hover {
  background-color: #c45656;
}

.btn-danger:disabled {
  background-color: #c0c4cc;
  cursor: not-allowed;
}

.btn-success {
  background-color: #67c23a;
  color: white;
}

.btn-success:hover {
  background-color: #529b2e;
}

.btn-info {
  background-color: #909399;
  color: white;
}

.btn-info:hover {
  background-color: #82848a;
}

.btn-warning {
  background-color: #e6a23c;
  color: white;
}

.btn-warning:hover {
  background-color: #cf9236;
}

/* 表格区域 */
.table-section {
  background: white;
  border-radius: 8px;
  margin-bottom: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  padding: 10px;
  position: relative;
  z-index: 5;
  min-height: 200px;
}

.table-section h3 {
  margin-bottom: 8px;
  color: #333;
  font-size: 14px;
}

.table-tips {
  background-color: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 6px;
  padding: 10px 15px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #0369a1;
}

.tip-icon {
  font-size: 16px;
  color: #409eff;
}

.table-container {
  overflow-x: auto;
  overflow-y: visible;
  max-height: none;
  position: relative;
  border-radius: 6px;
}

/* Element Plus表格样式 */
:deep(.el-table) {
  border-radius: 8px;
  font-size: 11px;
}

:deep(.el-table__body-wrapper) {
  overflow-x: auto;
  overflow-y: auto;
  min-width: 100%;
  scroll-behavior: smooth;
  -webkit-overflow-scrolling: touch;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-button) {
  border-radius: 6px;
}

:deep(.el-tag) {
  border-radius: 4px;
}

.no-data {
  text-align: center;
  color: #999;
  padding: 24px;
  font-size: 14px;
}

/* 单元格样式 */
.url-cell,
.params-cell,
.exception-cell {
  max-width: none;
  word-break: break-word;
  white-space: normal;
  line-height: 1.4;
}

/* 状态标签样式 */
.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.success {
  background-color: #f0f9ff;
  color: #67c23a;
}

.status-badge.error {
  background-color: #fef0f0;
  color: #f56c6c;
}

/* Element Plus标签样式增强 */
:deep(.el-tag--success) {
  background-color: #f0f9ff;
  border-color: #bae6fd;
  color: #67c23a;
}

:deep(.el-tag--danger) {
  background-color: #fef0f0;
  border-color: #fbc4c4;
  color: #f56c6c;
}

:deep(.el-tag--info) {
  background-color: #f4f4f5;
  border-color: #d3d4d6;
  color: #909399;
}

/* 分页 */
.pagination-section {
  background: white;
  border-radius: 8px;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  position: relative;
  z-index: 5;
  margin-top: 10px;
}

.pagination-info {
  color: #666;
}

.pagination-info .page-detail {
  margin-left: 15px;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination-controls select {
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 11px;
  height: 28px;
}

.pagination-buttons {
  display: flex;
  align-items: center;
  gap: 5px;
}

.page-btn {
  padding: 3px 6px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  min-width: 28px;
  text-align: center;
  font-size: 11px;
}

.page-btn:hover:not(:disabled) {
  background-color: #f5f7fa;
  border-color: #409eff;
}

.page-btn:disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}

.current-page {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.current-page:hover {
  background-color: #337ecc;
}

.page-ellipsis {
  padding: 4px 6px;
  color: #909399;
  font-size: 12px;
}

.page-jump {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-jump input {
  width: 52px;
  padding: 4px 6px;
  border: 1px solid #ddd;
  border-radius: 4px;
  text-align: center;
  height: 30px;
  font-size: 12px;
}

/* 错误信息和加载状态样式 */
.error-message {
  color: #f56c6c;
  background-color: #fef0f0;
  padding: 12px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-size: 13px;
  border: 1px solid #fbc4c4;
}

.error-icon {
  font-size: 18px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 32px;
  color: #606266;
  font-size: 14px;
}

.loading-spinner {
  border: 4px solid #f3f3f3;
  border-top: 4px solid #409eff;
  border-radius: 50%;
  width: 36px;
  height: 36px;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 调试信息 */
.debug-info {
  background-color: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 6px;
  padding: 12px;
  margin-bottom: 15px;
  font-size: 13px;
  color: #0369a1;
}

.debug-info p {
  margin: 4px 0;
}

/* 无数据状态 */
.no-data-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.no-data {
  text-align: center;
  color: #999;
  padding: 40px;
  font-size: 16px;
}

.no-data-hint {
  font-size: 14px;
  color: #666;
  margin-top: 10px;
}

/* 确保内容可见 */
.system-log-container * {
  box-sizing: border-box;
}

/* 修复可能的滚动问题 */
html, body {
  height: 100%;
  overflow-x: hidden;
}

/* 响应式设计优化 */
@media (max-width: 1400px) {
  .form-row {
    gap: 10px;
  }
  
  .form-item {
    min-width: 130px;
    max-width: 160px;
  }
  
  .form-item input[type="datetime-local"] {
    min-width: 130px;
    max-width: 160px;
  }
  
  .data-table {
    min-width: 1200px;
  }
}

@media (max-width: 1200px) {
  .form-row {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
  
  .form-item {
    min-width: 200px;
    max-width: 300px;
    flex: none;
  }
  
  .form-item input[type="datetime-local"] {
    min-width: 200px;
    max-width: 300px;
  }
  
  .checkbox-group {
    grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  }
  
  .data-table {
    min-width: 1000px;
  }
  
  .pagination-section {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .pagination-controls {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .action-buttons {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }
  
  .selection-info {
    margin-left: 0;
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .system-log-container {
    padding: 15px;
  }
  
  .search-section,
  .table-section,
  .pagination-section {
    padding: 15px;
  }
  
  .form-item {
    min-width: 100%;
    max-width: 100%;
  }
  
  .form-item input[type="datetime-local"] {
    min-width: 100%;
    max-width: 100%;
  }
  
  .action-buttons {
    justify-content: center;
  }
  
  .data-table {
    min-width: 800px;
  }
  
  .checkbox-group {
    grid-template-columns: repeat(auto-fit, minmax(90px, 1fr));
    gap: 6px;
    padding: 10px;
  }
  
  .checkbox-item {
    font-size: 12px;
    padding: 3px 6px;
  }
  
  .pagination-controls {
    gap: 10px;
  }
  
  .page-btn {
    padding: 4px 8px;
    min-width: 32px;
    font-size: 12px;
  }
  
  .selection-info {
    font-size: 12px;
    padding: 6px 10px;
  }
  
  .selection-count {
    font-size: 11px;
    padding: 1px 4px;
    min-width: 18px;
  }
  
  .table-tips {
    font-size: 12px;
    padding: 8px 12px;
    flex-direction: column;
    text-align: center;
    gap: 5px;
  }
}

/* 列设置对话框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
  width: 600px;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  background-color: #fafafa;
}

.modal-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  transition: color 0.2s;
}

.close-btn:hover {
  color: #666;
}

.modal-body {
  padding: 20px;
  overflow-y: auto;
  flex-grow: 1;
}

.column-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.column-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  transition: all 0.2s;
  cursor: move;
}

.column-item:hover {
  background-color: #e9ecef;
  border-color: #409eff;
}

.column-item.dragging {
  opacity: 0.5;
  transform: rotate(5deg);
}

.column-item.drag-over {
  border-color: #409eff;
  background-color: #e6f7ff;
}

.drag-handle {
  color: #999;
  font-size: 16px;
  cursor: move;
  user-select: none;
  padding: 2px;
}

.drag-handle:hover {
  color: #409eff;
}

.column-checkbox {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  flex-grow: 1;
}

.column-checkbox input[type="checkbox"] {
  width: 18px;
  height: 18px;
  accent-color: #409eff;
}

.column-number {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  min-width: 20px;
}

.column-label {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 20px;
  border-top: 1px solid #eee;
  background-color: #fafafa;
}

.modal-footer .btn {
  padding: 8px 16px;
}

/* 排序图标样式 */
.sort-icon {
  cursor: pointer;
  margin-left: 5px;
  font-size: 12px;
  color: #909399;
  transition: color 0.2s;
}

.sort-icon:hover {
  color: #409eff;
}

/* 响应式设计优化 */
@media (max-width: 768px) {
  .modal-content {
    width: 90%;
    max-width: 500px;
  }
  
  .column-item {
    padding: 10px;
  }
  
  .column-checkbox {
    gap: 10px;
  }
  
  .modal-footer {
    flex-direction: column;
    gap: 8px;
  }
  
  .modal-footer .btn {
    width: 100%;
  }
  
  /* 删除确认和结果对话框的移动端优化 */
  .delete-confirm-modal,
  .delete-result-modal {
    width: 95%;
    max-width: 400px;
  }
  
  .delete-confirm-content,
  .delete-result-content {
    gap: 10px;
  }
  
  .warning-icon,
  .success-icon,
  .error-icon {
    font-size: 36px;
  }
  
  .confirm-message,
  .result-message {
    font-size: 14px;
  }
  
  .selected-ids,
  .failed-ids,
  .delete-reason,
  .operation-time {
    font-size: 13px;
    margin-top: 10px;
  }
  
  /* 导出对话框的移动端优化 */
  .export-success-modal,
  .export-error-modal {
    width: 95%;
    max-width: 400px;
  }
  
  .export-success-content,
  .export-error-content {
    gap: 10px;
  }
  
  .export-success-content .success-icon,
  .export-error-content .error-icon {
    font-size: 36px;
  }
  
  .export-success-content p,
  .export-error-content p {
    font-size: 14px;
  }
}

/* 批量删除确认对话框样式 */
.delete-confirm-modal .modal-header {
  background-color: #fffbe6;
  border-bottom: 1px solid #ffe58f;
}

.delete-confirm-modal .delete-header h3 {
  color: #faad14;
}

.delete-confirm-modal .modal-body {
  padding: 20px;
  text-align: center;
}

.delete-confirm-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.warning-icon {
  font-size: 48px;
  color: #faad14;
}

.confirm-message {
  text-align: left;
  line-height: 1.6;
}

.main-text {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.highlight-count {
  font-weight: 600;
  color: #f56c6c;
}

.warning-text {
  font-size: 14px;
  color: #faad14;
  margin-top: 5px;
}

.selected-ids {
  margin-top: 15px;
  font-size: 14px;
  color: #52c41a;
  font-weight: 500;
}

.label {
  font-weight: 500;
  color: #333;
}

.ids {
  font-weight: 600;
  color: #f56c6c;
}

/* 删除结果对话框样式 */
.delete-result-modal .modal-header {
  background-color: #f6ffed;
  border-bottom: 1px solid #b7eb8f;
}

.delete-result-modal .success-header h3 {
  color: #52c41a;
}

.delete-result-modal .error-header h3 {
  color: #f5222d;
}

.delete-result-modal .modal-body {
  padding: 20px;
  text-align: center;
}

.delete-result-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.success-icon,
.error-icon {
  font-size: 48px;
  color: #52c41a; /* 成功为绿色，失败为红色 */
}

.delete-result-content .error-icon {
  color: #f5222d;
}

.result-message {
  text-align: left;
  line-height: 1.6;
}

.result-summary {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.result-summary ul {
  list-style: none;
  padding: 0;
  margin: 10px 0;
}

.result-summary li {
  margin-bottom: 5px;
  color: #666;
}

.success-count,
.error-count {
  font-weight: 600;
  color: #52c41a; /* 成功为绿色，失败为红色 */
}

.delete-result-content .error-count {
  color: #f5222d;
}

.failed-ids {
  margin-top: 15px;
  font-size: 14px;
  color: #faad14;
  font-weight: 500;
}

.failed-ids-list {
  font-weight: 600;
  color: #f56c6c;
}

.delete-reason {
  margin-top: 15px;
  font-size: 14px;
  color: #faad14;
  font-weight: 500;
}

.reason-text {
  font-weight: 600;
  color: #f56c6c;
}

.operation-time {
  margin-top: 15px;
  font-size: 14px;
  color: #909399;
  font-style: italic;
}

.time-text {
  font-weight: 500;
  color: #333;
}

/* 导出成功和失败提示对话框样式 */
.export-success-modal .modal-header {
  background-color: #f6ffed;
  border-bottom: 1px solid #b7eb8f;
}

.export-success-modal .modal-header h3 {
  color: #52c41a;
}

.export-error-modal .modal-header {
  background-color: #fff2f0;
  border-bottom: 1px solid #ffccc7;
}

.export-error-modal .modal-header h3 {
  color: #f5222d;
}

.export-success-content,
.export-error-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  text-align: center;
}

.export-success-content .success-icon {
  font-size: 48px;
  color: #52c41a;
}

.export-error-content .error-icon {
  font-size: 48px;
  color: #f5222d;
}

.export-success-content p,
.export-error-content p {
  font-size: 16px;
  line-height: 1.6;
  color: #333;
  white-space: pre-line;
  text-align: left;
}
</style>
